<template>
  <el-dialog
    v-model="props.show"
    width="800px"
    :append-to-body="true"
    :destroy-on-close="true"
    :before-close="close"
  >
    <template #default>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
        class="user-editor-form"
      >
        <el-form-item label="用户名称" prop="username" class="inline">
          <el-input
            v-model="form.username"
            :maxlength="16"
            show-word-limit
            placeholder="请输入用户名称"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" class="inline">
          <el-input
            v-model="form.password"
            :maxlength="30"
            show-word-limit
            show-password
            placeholder="请输入用户密码"
          />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName" class="inline">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email" class="inline">
          <el-input v-model="form.email" placeholder="请输入用户邮箱" />
        </el-form-item>

        <el-form-item label="性别" prop="gender" class="inline">
          <el-select v-model="form.gender" placeholder="请选择用户性别">
            <el-option
              v-for="item in system_global_gender"
              :key="item.v"
              :label="item.k"
              :value="item.v"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone" class="inline">
          <el-input v-model="form.phone" placeholder="请输入用户手机号码" />
        </el-form-item>

        <el-form-item label="账号状态" prop="enabled" class="inline">
          <el-radio-group v-model="form.enabled" class="ml-4">
            <el-radio
              v-for="item in system_global_status"
              :key="item.v"
              :value="item.v"
              >{{ item.k }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属机构" prop="unitId" class="inline">
          <el-tree-select
            v-model="form.unitId"
            placeholder="请选择所属机构"
            :render-after-expand="false"
            :data="unitTreeList"
            :props="{ label: 'name' }"
            :check-strictly="true"
            :auto-expand-parent="true"
            :default-expand-all="true"
            node-key="id"
          />
        </el-form-item>

        <el-form-item label="所属岗位" prop="postIds" class="inline">
          <el-tree-select
            v-model="form.postIds"
            placeholder="请选择所属岗位"
            :render-after-expand="false"
            :data="postTree"
            :props="{ label: 'postName' }"
            :auto-expand-parent="true"
            :default-expand-all="true"
            node-key="id"
            show-checkbox
            multiple
          />
        </el-form-item>

        <el-form-item label="分配角色" prop="roleIds" class="inline">
          <el-tree-select
            v-model="form.roleIds"
            placeholder="请选择分配角色"
            :render-after-expand="false"
            :data="roleTree"
            :props="{ label: 'roleName' }"
            :auto-expand-parent="true"
            :default-expand-all="true"
            node-key="id"
            show-checkbox
            multiple
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入用户备注"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="onSubmit"> 确认 </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onBeforeMount,watch } from "vue";
import { unitTree, postAll, roleAll, userGet, userAdd, userUpdate, userDelete } from "./api/user";
import {roleGet} from '@/utils/api/system'
const props = defineProps({
  show: Boolean,
  id: String,
  type: Number
});
const emit = defineEmits();

const form = reactive({
  id: "", //修改用户的提交给后端的参数
  avatar:'', //修改用户的提交给后端的参数
  username: "",
  password: "",
  phone: "",
  realName: "",
  gender: "",
  enabled: "",
  remark: "",
  email: "",
  roleIds: [],
  postIds: [],
  unitId: "",
});
const postTree = ref([]);
const roleTree = ref([]);
const unitTreeList = ref([]);
const system_global_gender = [
  { v: 0, k: "女" },
  { v: 1, k: "男" },
];
const system_global_status = [
  { v: 1, k: "启用" },
  { v: 0, k: "禁用" },
];
// watch(() => props.id, (newId) => {
//   if (newId) {
//     getUserData();
//   }
// });
if(props.id){
  getUserData()
}
// 修改角色
async function getUserData(){
  let userData = await userGet(props.id);
  let { username, phone, avatar,realName,gender,enabled,remark,email,unitId } = userData.data.user;
  Object.assign(form, { username,phone, realName,gender,enabled,remark,email,unitId,roleIds:userData.data.roleIds,postIds:userData.data.postIds });
}
// 生命周期
onBeforeMount(async () => {
  init();
});

const init = () => {
  Promise.all([
    unitTree().then((res) => (unitTreeList.value = res.data)),
    postAll().then((res) => (postTree.value = res.data)),
    roleAll().then((res) => (roleTree.value = res.data)),
  ]);
};

// 关闭dialog（点击取消 或 x）
const close = () => {
  ElMessageBox.confirm("Are you sure?").then(() => {
    ElMessage({ type: "success", message: "操作成功" });
    emit("update:show", false);
  });
};
// 提交表单
const onSubmit = async () => {
  let {id,avatar,username,password,phone,realName,gender,enabled,remark,email,roleIds,postIds,unitId} = form
  const params = {username,password,phone,realName,gender,enabled,remark,email,roleIds,postIds,unitId}
  if (props.type === 2) {
    await userUpdate({id:props.id,avatar,...params})
  }else if(props.type === 1){
    await userAdd(params);
  }
  
  emit("change");
  emit("update:show", false);
};
</script>
<style lang="scss" scoped>
.user-editor-form {
  :deep(.inline) {
    display: inline-flex;
    vertical-align: middle;
    width: 50%;
  }

  .treeList {
    padding: 2px;
    width: 100%;
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
      inset;
  }
}
</style>
